// src/pages/UserList/index.tsx
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  DownOutlined,
  EditOutlined,
  InfoCircleOutlined,
  KeyOutlined,
  PlusOutlined,
  SettingOutlined,
  UserAddOutlined,
} from '@ant-design/icons';
import {
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import {
  Button,
  Divider,
  Dropdown,
  Modal,
  Popconfirm,
  Space,
  Tag,
  message,
} from 'antd';
import React, { useRef, useState } from 'react';
import {
  checkEmail,
  checkPhone,
  checkUsername,
  //   deleteUser,
  deleteUserBatch,
  frozenBatch,
  getUserList,
  updateUserStatus,
} from '@/services/user';
import { useModel } from '@umijs/max';
import PasswordModal from './components/PasswordModal';
import SysUserAgentModal from './components/SysUserAgentModal';
import UserModal from './components/UserModal';

import SelectRoleModal from '@/pages/UserList/components/SelectRoleModal';
import { callApi, handleProTableRequest } from '@/utils/request';
import AuthorizedButton from '@/components/AuthorizedButton';
import { UserItem, UserQueryParams } from '@/types/user';

const UserList: React.FC = () => {
  const actionRef = useRef<any>(null);
  const { initialState } = useModel('@@initialState');

  const [selectedRowsState, setSelectedRows] = useState<UserItem[]>([]);
  const [userModalVisible, setUserModalVisible] = useState<boolean>(false);
  const [roleModalVisible, setRoleModalVisible] = useState<boolean>(false);
  const [passwordModalVisible, setPasswordModalVisible] =
      useState<boolean>(false);
  const [agentModalVisible, setAgentModalVisible] = useState<boolean>(false);
  const [currentUser, setCurrentUser] = useState<UserItem | undefined>(
      undefined,
  );
  const [currentUserId, setCurrentUserId] = useState<number | string>('');
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [disableSubmit, setDisableSubmit] = useState<boolean>(false);
  const [expandedFilter, setExpandedFilter] = useState<boolean>(false); // 控制查询表单展开收起

  // --- 操作方法 ---

  const handleAdd = () => {
    setIsEdit(false);
    setDisableSubmit(false);
    setCurrentUser(undefined);
    setCurrentUserId('');
    setUserModalVisible(true);
  };

  const handleEdit = (record: UserItem) => {
    setIsEdit(true);
    setDisableSubmit(false);
    setCurrentUser(record);
    setCurrentUserId(record.id.toString());
    setUserModalVisible(true);
  };

  const handleDetail = (record: UserItem) => {
    setIsEdit(true);
    setDisableSubmit(true);
    setCurrentUser(record);
    setCurrentUserId(record.id.toString());
    setUserModalVisible(true);
  };

  const handleBatchDelete = () => {
    if (selectedRowsState.length === 0) {
      message.warning('请选择至少一条记录');
      return;
    }
    Modal.confirm({
      title: '确认批量删除',
      content: `您确定要删除选中的 ${selectedRowsState.length} 条记录吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const ids = selectedRowsState.map((item) => item.id).join(',');
        const result = await callApi(
            () => deleteUserBatch({ ids }),
            { successMsg: '批量删除成功', errorMsg: '批量删除失败' }
        );

        if (result && actionRef.current && actionRef.current.reloadAndRest) {
          await actionRef.current.reloadAndRest(); // 重置并刷新表格
        }
      },
    });
  };

  const handleBatchFreeze = (status: number) => {
    if (selectedRowsState.length === 0) {
      message.warning('请选择至少一条记录');
      return;
    }
    const statusText = status === 1 ? '解冻' : '冻结';
    const ids = selectedRowsState.map((item) => item.id).join(',');
    Modal.confirm({
      title: `确认批量${statusText}`,
      content: `您确定要批量${statusText}选中的 ${selectedRowsState.length} 条记录吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const result = await callApi(
            () => frozenBatch({ ids, status }),
            { successMsg: `批量${statusText}成功`, errorMsg: `批量${statusText}失败` }
        );

        if (result && actionRef.current && actionRef.current.reloadAndRest) {
          await actionRef.current.reloadAndRest();
        }
      },
    });
  };

  const handleResetPassword = (record: UserItem) => {
    setCurrentUser(record);
    setPasswordModalVisible(true);
  };

  const handleAssignAgent = (record: UserItem) => {
    setCurrentUser(record);
    setAgentModalVisible(true);
  };

  const handleOpenRoleModal = (record: UserItem) => {
    setCurrentUser(record);
    setRoleModalVisible(true);
  };

  const handleFreeze = (record: UserItem, status: number) => {
    const statusText = status === 1 ? '解冻' : '冻结';
    Modal.confirm({
      title: `确认${statusText}`,
      content: `您确定要${statusText}用户 "${record.account}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const result = await callApi(
            () => updateUserStatus({ id: record.id.toString(), status }),
            { successMsg: `${statusText}成功`, errorMsg: `${statusText}失败` }
        );

        if (result && actionRef.current && actionRef.current.reload) {
          await actionRef.current.reload();
        }
      },
    });
  };

  // --- 修正：将 handleModalOk 定义为 async 函数 ---
  const handleModalOk = async (formData: any) => {
    // 处理 UserModal 的确定事件
    console.log('UserModal OK:', formData);
    setUserModalVisible(false);
    // --- 修正：使用 null 检查，并等待 Promise ---
    if (actionRef.current && actionRef.current.reload) {
      await actionRef.current.reload(); // 重新加载表格
    }
  };

  const handlePasswordModalOk = (formData: any) => {
    // 处理 PasswordModal 的确定事件
    console.log('PasswordModal OK:', formData);
    setPasswordModalVisible(false);
    message.success('密码重置成功');
  };

  const handleAgentModalOk = (formData: any) => {
    // 处理 SysUserAgentModal 的确定事件
    console.log('SysUserAgentModal OK:', formData);
    setAgentModalVisible(false);
    message.success('代理设置成功');
  };

  const handleModalCancel = () => {
    setUserModalVisible(false);
    setPasswordModalVisible(false);
    setAgentModalVisible(false);
  };

  // --- 导出 ---
  const handleExport = () => {
    // 实现导出逻辑，例如调用 API 获取文件流
    console.log('Export clicked');
    message.info('导出功能待实现');
  };

  // --- 导入 ---
  const handleImport = () => {
    // 实现导入逻辑，例如打开上传文件的弹窗
    console.log('Import clicked');
    message.info('导入功能待实现');
  };

  // --- 同步用户 ---
  const handleSyncUser = () => {
    // 实现同步用户逻辑
    console.log('Sync User clicked');
    message.info('同步用户功能待实现');
  };

  // 列定义
  const columns: ProColumns<UserItem>[] = [
    {
      title: '用户账号',
      dataIndex: 'account',
      width: 120,
      formItemProps: {
        // 查询表单项配置
      },
      render: (text) => text || '-',
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      width: 100,
      formItemProps: {
        // 查询表单项配置
      },
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: 80,
      valueType: 'select',
      valueEnum: {
        0: { text: '未知' },
        1: { text: '男' },
        2: { text: '女' },
      },
      search: false, // 不在查询表单中显示
      render: (_, record) => {
        const sexMap = { 0: '未知', 1: '男', 2: '女' };
        return sexMap[record.sex as keyof typeof sexMap] || '-';
      },
    },
    {
      title: '手机号码',
      dataIndex: 'phone',
      width: 120,
      formItemProps: {
        // 查询表单项配置
      },
      render: (text) => text || '-',
    },
    {
      title: '身份证号',
      dataIndex: 'idCard',
      width: 150,
      formItemProps: {
        // 查询表单项配置
      },
      render: (text) => text || '-',
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      width: 150,
      render: (text) => text || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      valueType: 'select',
      valueEnum: {
        1: { text: '正常', status: 'Success' },
        2: { text: '冻结', status: 'Default' },
      },
      search: false, // 不在查询表单中显示
      render: (_, record) => (
          <Tag color={record.status === 1 ? 'success' : 'default'}>
            {record.status === 1 ? '正常' : '冻结'}
          </Tag>
      ),
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 170,
      fixed: 'right',
      render: (_, record) => (
          <Space split={<Divider type="vertical" />} size={0}>
            <AuthorizedButton
                type="link"
                size="small"
                onClick={() => handleDetail(record)}
                code="user_list_detail_btn" // 替换为实际权限码
            >
              详情
            </AuthorizedButton>
            <Dropdown
                menu={{
                  items: [
                    {
                      key: 'edit',
                      label: '编辑',
                      onClick: () => handleEdit(record),
                    },
                    {
                      key: 'resetPassword',
                      label: '重置密码',
                      onClick: () => handleResetPassword(record),
                    },
                    {
                      key: record.status === 1 ? 'freeze' : 'unfreeze',
                      label: record.status === 1 ? '冻结' : '解冻',
                      icon: record.status === 1 ? <CloseCircleOutlined /> : <CheckCircleOutlined />,
                      danger: record.status === 1,
                      onClick: () => handleFreeze(record, record.status === 1 ? 2 : 1), // 切换状态
                    },
                    {
                      key: 'agent',
                      label: '分配代理',
                      onClick: () => handleAssignAgent(record),
                    },
                    {
                      key: 'role',
                      label: '分配角色',
                      onClick: () => handleOpenRoleModal(record),
                    },
                  ],
                }}
                trigger={['click']}
            >
              <AuthorizedButton
                  type="link"
                  size="small"
                  code="user_list_more_btn" // 替换为实际权限码
              >
                更多 <DownOutlined />
              </AuthorizedButton>
            </Dropdown>
          </Space>
      ),
    },
  ];

  return (
      <PageContainer>
        <ProTable<UserItem, UserQueryParams>
            headerTitle="用户管理"
            actionRef={actionRef}
            rowKey="id"
            search={{
              labelWidth: 'auto',
              collapsed: !expandedFilter, // 控制展开收起
              onCollapse: setExpandedFilter, // 更新展开状态
            }}
            toolBarRender={() => [
              <AuthorizedButton
                  key="add"
                  type="primary"
                  onClick={handleAdd}
                  code="user_list_add_btn" // 替换为实际权限码
              >
                <PlusOutlined />
                新建
              </AuthorizedButton>,
            ]}
            tableAlertRender={({ selectedRowKeys }) =>
                selectedRowKeys.length > 0 && (
                    <Space size={24}>
                      <span>已选 {selectedRowKeys.length} 项</span>
                      <AuthorizedButton
                          type="link"
                          onClick={() => handleBatchFreeze(2)}
                          danger
                          code="user_list_batch_freeze_btn" // 替换为实际权限码
                      >
                        批量冻结
                      </AuthorizedButton>
                      <AuthorizedButton
                          type="link"
                          onClick={() => handleBatchFreeze(1)}
                          code="user_list_batch_unfreeze_btn" // 替换为实际权限码
                      >
                        批量解冻
                      </AuthorizedButton>
                      <AuthorizedButton
                          type="link"
                          onClick={handleBatchDelete}
                          danger
                          code="user_list_batch_delete_btn" // 替换为实际权限码
                      >
                        批量删除
                      </AuthorizedButton>
                    </Space>
                )
            }
            request={async (params, sorter) => {
              // 构造查询参数
              const queryParams: UserQueryParams = {
                pageNum: params.current,
                pageSize: params.pageSize,
                companyId: initialState?.currentUser?.companyId,
              };
              // 处理排序
              if (Object.keys(sorter).length > 0) {
                const sortField = Object.keys(sorter)[0];
                const sortOrder = sorter[sortField]; // 'ascend' or 'descend'
                queryParams.sortField = sortField;
                queryParams.sortOrder = sortOrder === 'ascend' ? 'asc' : 'desc';
              }
              // 处理过滤 (filters)
              // 根据实际情况处理 filter 参数

              return handleProTableRequest<UserItem>(
                  () => getUserList(queryParams),
                  { errorMsg: '获取用户列表失败' }
              );
            }}
            columns={columns}
            rowSelection={{
              onChange: (selectedRowKeys, selectedRows) => {
                setSelectedRows(selectedRows);
              },
            }}
            pagination={{
              defaultPageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              pageSizeOptions: ['10', '20', '30'],
            }}
        />

        {/* User Modal */}
        <UserModal
            visible={userModalVisible}
            isEdit={isEdit}
            disableSubmit={disableSubmit}
            currentUserId={currentUserId.toString()}
            currentUser={currentUser}
            onOk={handleModalOk}
            onCancel={handleModalCancel}
            checkUsername={checkUsername}
            checkPhone={checkPhone}
            checkEmail={checkEmail}
        />

        {/* Password Modal */}
        <PasswordModal
            visible={passwordModalVisible}
            currentUser={currentUser}
            onOk={handlePasswordModalOk}
            onCancel={handleModalCancel}
        />

        {/* Sys User Agent Modal */}
        <SysUserAgentModal
            visible={agentModalVisible}
            currentUser={currentUser}
            onOk={handleAgentModalOk}
            onCancel={handleModalCancel}
        />

        {/* 角色列表模态框 */}
        {currentUser && (
            <SelectRoleModal
                visible={roleModalVisible}
                queryType={1}
                canOperate={true}
                curUserId={currentUser.id}
                curUserRealName={currentUser.realName}
                onOk={() => {
                  setRoleModalVisible(false);
                }}
                onCancel={() => {
                  setRoleModalVisible(false);
                }}
            />
        )}
      </PageContainer>
  );
};

export default UserList;